package com.lxp.userms.controller;

import com.lxp.userms.entity.*;
import com.lxp.userms.mapper.CategoryMapper;
import com.lxp.userms.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/post")
public class PostController {
    @Autowired
    private  ExpertAnswerService expertAnswerService;
    @Autowired
    private QuestionService questionService;
    @Autowired
    private PostService postService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private UserService userService; // 注入UserService用于获取用户信息
    @GetMapping("/publish")
    public String showPublishPage(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (!checkAdmin(user)) {
            return "redirect:/user/login"; // 非管理员用户重定向到登录页
        }
        return "publish_post";
    }
    
    /**
     * 检查用户是否为管理员
     */
    private boolean checkAdmin(User user) {
        return user != null && "admin".equals(user.getUsername());
    }

    @GetMapping("/category/list")
    public String categoryList(Model model) {
        List<Category> categories = categoryService.getAllCategories();
        model.addAttribute("categories", categories);
        return "category_list";
    }

    @PostMapping("/category/add")
    public String addCategory(@RequestParam String name, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null || user.getRole() != 2) {
            return "redirect:/user/login";
        }
        Category category = new Category();
        category.setName(name);
        categoryService.addCategory(category);
        return "redirect:/post/category/list";
    }

    @GetMapping("/category/delete/{id}")
    public String deleteCategory(@PathVariable int id, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null || user.getRole() != 2) {
            return "redirect:/user/login";
        }

        // 获取该分类下的所有问题
        List<Question> questions = questionService.getQuestionsByCategoryId(id);
        
        // 删除每个问题下的答案
        for (Question q : questions) {
            expertAnswerService.deleteAnswersByQuestionId(q.getId());
        }

        // 删除问题、帖子和分类
        questionService.deleteQuestionsByCategoryId(id);
        postService.deletePostsByCategoryId(id);
        categoryService.deleteCategoryById(id);
        
        return "redirect:/post/category/list";
    }
    @GetMapping("/category/{id}")
    public String getPostsByCategory(@PathVariable int id, Model model) {
        List<Post> posts = postService.getPostsByCategoryId(id);
        model.addAttribute("posts", posts);
        return "post_list_category"; // 确保存在该 JSP 页面
    }
    @GetMapping("/search")
    public String searchPosts(@RequestParam String keyword, Model model) {
        List<Post> posts = postService.searchPostsByKeyword(keyword);
        model.addAttribute("posts", posts);
        model.addAttribute("keyword", keyword);
        return "post_list_search";
    }

    @PostMapping("/publish")
    public String publishPost(Post post, 
                              @RequestParam("imageFile") MultipartFile imageFile,
                              @RequestParam("videoFile") MultipartFile videoFile,
                              HttpSession session) {
        User user = (User) session.getAttribute("user"); // 从会话中获取用户信息
        if (user != null) {
            post.setUserId(user.getId()); // 设置帖子的用户ID

            // 处理图片上传
            if (!imageFile.isEmpty()) {
                String fileName = System.currentTimeMillis() + "_" + imageFile.getOriginalFilename();
                String uploadDir = session.getServletContext().getRealPath("/uploads/images");
                File dir = new File(uploadDir);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                try {
                    imageFile.transferTo(new File(uploadDir, fileName));
                    post.setImageUrl("/uploads/images/" + fileName);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            // 处理视频上传
            if (!videoFile.isEmpty()) {
                String fileName = System.currentTimeMillis() + "_" + videoFile.getOriginalFilename();
                String uploadDir = session.getServletContext().getRealPath("/uploads/videos");
                File dir = new File(uploadDir);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                try {
                    videoFile.transferTo(new File(uploadDir, fileName));
                    post.setVideoUrl("/uploads/videos/" + fileName);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            postService.publishPost(post);
            return "redirect:/post/list";
        } else {
            return "redirect:/user/login"; // 如果未登录，重定向到登录页面
        }
    }

    @GetMapping("/list")
    public String postList(Model model) {
        List<Post> posts = postService.getAllPosts();
        model.addAttribute("posts", posts);
        return "post_list";
    }

    @GetMapping("/detail/{id}")
    public String postDetail(@PathVariable int id, Model model, HttpSession session) {
        Post post = postService.getPostById(id);
        model.addAttribute("post", post);

        // 查询评论列表
        List<Comment> comments = commentService.getCommentsByPostId(id);
        model.addAttribute("comments", comments);

        // 查询点赞数和收藏数
        model.addAttribute("likeCount", likeService.getLikeCount(id));
        model.addAttribute("favoriteCount", favoriteService.getFavoriteCount(id));

        return "post_detail";
    }

    @GetMapping("/edit/{id}")
    public String showEditPage(@PathVariable int id, Model model) {
        Post post = postService.getPostById(id);
        model.addAttribute("post", post);
        return "edit_post";
    }

    @PostMapping("/update")
    public String updatePost(Post post, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (!checkAdmin(user)) {
            return "redirect:/user/login"; // 非管理员用户重定向到登录页
        }
        
        postService.updatePost(post);
        return "redirect:/post/detail/" + post.getId();
    }

    @GetMapping("/delete/{id}")
    public String deletePost(@PathVariable int id, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (!checkAdmin(user)) {
            return "redirect:/user/login"; // 非管理员用户重定向到登录页
        }
        
        postService.deletePost(id);
        return "redirect:/post/list";
    }

    @Autowired
    private CommentService commentService;

    @PostMapping("/comment")
    public String addComment(int postId, String content, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login"; // 用户未登录，跳转到登录页
        }
        Comment comment = new Comment();
        comment.setPostId(postId);
        comment.setContent(content);
        comment.setUserId(user.getId()); // 设置用户ID
        comment.setCreateTime(new java.util.Date()); // 设置评论时间

        // 在实际项目中还需要设置 userId 和 createTime
        commentService.addComment(comment);
        return "redirect:/post/detail/" + postId;
    }

    @Autowired
    private LikeService likeService;

    @PostMapping("/like")
    public String likePost(int postId, int userId) {
        Like like = new Like();
        like.setPostId(postId);
        like.setUserId(userId);
        likeService.addLike(like);
        return "redirect:/post/detail/" + postId;
    }

    @PostMapping("/unlike")
    public String unlikePost(int postId, int userId) {
        likeService.removeLike(postId, userId); // 调用删除点赞方法
        return "redirect:/post/detail/" + postId;
    }

    @Autowired
    private FavoriteService favoriteService;

    @PostMapping("/favorite")
    public String favoritePost(int postId, int userId) {
        Favorite favorite = new Favorite();
        favorite.setPostId(postId);
        favorite.setUserId(userId);
        favoriteService.addFavorite(favorite);
        return "redirect:/post/detail/" + postId;
    }

    @PostMapping("/unfavorite")
    public String unfavoritePost(int postId, int userId) {
        favoriteService.removeFavorite(postId, userId); // 调用删除收藏方法
        return "redirect:/post/detail/" + postId;
    }
}